#include <stddef.h>
#include <stdio.h>

/**************************************************
This file contains general purpose helper functions
**************************************************/


/*
input:
	str     - pointer to string
	split   - byte-separator
	bufsize - size of buf
output:
	buf     - pointer to buf, where part of the string will be stored
	offset  - pointer to var, where input offset will be saved
return:
	neg on error
	0 if that part is last
	1 if that part not last
*/
int parserCore( const char* str, char split, char* buf, size_t bufsize, size_t* offset ){
	
	register size_t i;
	register size_t p;
	
	//init some vars
	p = *offset;
	
	for( i = 0; i < bufsize; i++ ){
		//read byte from input
		buf[i] = str[p];
		p++;
		
		//if end of string
		if( !buf[i] ){
			*offset = p;
			return 0;
		}
		
		//if this byte equal split
		if( buf[i] == split ){
			buf[i] = 0x00;
			*offset = p;
			return 1;
		}
	}
	
	return -1;
}


static const char* const readableSizeStrings[] = { 
	"%.0f B",   "%.2f KiB", "%.2f MiB", "%.2f GiB", 
	"%.2f TiB", "%.2f PiB", "%.2f EiB", NULL };
void readableSize( char* buf, off_t bytes ){
	
	int i;
	double size = bytes;
	
	for( i = 0; size > 1023 && readableSizeStrings[i+1]; i++ ) size /= 1024;
	
	sprintf( buf, readableSizeStrings[i], size );
}


/*
str - pointer to input string
buf - pointer to output encoded uri
bufsize - length of buf
*/
int uriEncode( const char* str, char* buf, int bufsize ){
	
	int i;
	int res;
	int offset;
	
	offset = 0;
	
	for( i = 0; offset < bufsize; i++ ){
		
		if( !str[i] ){
			buf[offset] = 0x00;
			return offset;
		}
		
		if( offset + 4 > bufsize ) return -2;
		
		res = sprintf( buf + offset, "%%%02hhX", str[i] );
		if( res != 3 ){
			perror( "uri encode sprintf" );
			return -2;
		}
		
		offset += 3;
	}
	
	return -2;
}
